package dao.Sale;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import model.Sale;
import abstractFactory.Factory;

public class SaleDAOJPA implements SaleDAO{
	static EntityManager manager;

	public EntityManager getManager() {
		if(manager == null) {
			manager = Factory.getFactory().createEntityManager();
		}
		return manager;
	}

	public boolean save(Sale sale) {
		try	{
			getManager().getTransaction().begin();		
			getManager().persist(sale);
			getManager().getTransaction().commit();
			return true;
		}catch (Exception e) {
			return false;
		}
	}

	public boolean update(Sale sale){
		try{
			getManager().getTransaction().begin();
			getManager().merge(sale);
			getManager().getTransaction().commit();
			return true;
		}catch (Exception e) {
			return false;
		}
	}

	public boolean delete(Sale sale){
		try {
			Sale s = getManager().find(Sale.class, sale.getId());
			getManager().getTransaction().begin();
			getManager().remove(s);
			getManager().getTransaction().commit();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public List<Sale> getAllSales(){
		Query query = (Query) getManager().createQuery("SELECT s FROM Sale s" );
		@SuppressWarnings("unchecked")
		List<Sale> sales =  query.getResultList();
		return sales;
	}

	public Long getTotalSales(){
		Query query = (Query) getManager().createQuery("SELECT count(s) FROM Sale s" );
		Long total = (Long) query.getSingleResult();
		return total;
	}

	public Sale getSaleById(int id)	{
		try {
			Sale sale = getManager().find(Sale.class, id);
			return sale;
		} catch (Exception e) {
			return null;				
		}
	}
}
